package com.zhanghe.im.handler;

import com.zhanghe.im.protocol.command.PacketCodeC;
import com.zhanghe.im.request.LoginRequestPacket;
import com.zhanghe.im.response.LoginResponsePacket;
import com.zhanghe.im.session.Session;
import com.zhanghe.im.util.LoginUtil;
import com.zhanghe.im.util.SessionUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;
import java.util.UUID;

/**
 * SimpleLoginRequestHandler
 *
 * @author Clevo
 * @date 2018/10/23
 */
public class SimpleLoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginRequestPacket loginRequestPacket) throws Exception {
        //登录逻辑
        LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
        loginResponsePacket.setVersion(loginRequestPacket.getVersion());
        if(valid(loginRequestPacket)){
//            LoginUtil.markLogin(channelHandlerContext.channel());
            System.out.println("用户["+loginRequestPacket.getUserName()+"]登陆成功.");
            Session session = new Session();
            session.setUserId(randomUserId());
            session.setUserName(loginRequestPacket.getUserName());
            SessionUtil.bindSession(session,channelHandlerContext.channel());
            loginResponsePacket.setSuccess(true);
            loginResponsePacket.setUserId(session.getUserId());
            loginResponsePacket.setUserName(session.getUserName());

            System.out.println("用户["+loginRequestPacket.getUserName()+"]userID:"+session.getUserId());
        }else{
            loginResponsePacket.setSuccess(false);
            loginResponsePacket.setReason("密码错误");
        }
        channelHandlerContext.channel().writeAndFlush(loginResponsePacket);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Session session = SessionUtil.getSession(ctx.channel());
        if(session!=null) {
            System.out.println("用户[" + session.getUserName() + "]退出.");
            SessionUtil.unbindSession(session, ctx.channel());
        }
        super.channelInactive(ctx);
    }

    public boolean valid(LoginRequestPacket loginRequestPacket){
        return true;
    }

    public String randomUserId(){
        return UUID.randomUUID().toString();
    }
}
